package org.jeecg.common.system.base.controller;

import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.properties.config.JeecgPropertyConfig;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ReflectHelper;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class BaseController<VO> {

    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @Autowired
    protected JeecgPropertyConfig jeecgPropertyConfig;

    /**
     * 模版下载
     *
     * @param request
     * @param title
     * @return
     */
//    @AutoLog(value = "客户管理-分页列表查询")
    @ApiOperation(value = "模版下载", notes = "模版下载")
    @GetMapping(value = "/exportXlsTemplate")
    public ModelAndView exportXlsTemplate(HttpServletRequest request, @RequestParam(name = "title", required = true) String title) {
        Class<VO> tClass = (Class<VO>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return this.exportXls(title, new ArrayList<VO>(), tClass, false);
    }

    /**
     * 生成导出信息
     *
     * @param title
     * @param list
     * @param tClass
     * @return
     */
//    protected ModelAndView exportXls(String title, List<VO> list, Class<VO> tClass) {
//    protected ModelAndView exportXls(String title, List<?> list, Class<?> tClass) {
    protected <VO1> ModelAndView exportXls(String title, List<VO1> list, Class<VO1> tClass) {
        return this.exportXls(title, list, tClass, false);
    }

    protected <VO1> ModelAndView exportXls(String title, List<VO1> list, Class<VO1> tClass, boolean addIndex) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        ExportParams exportParams = new ExportParams(title, "导出人:" + sysUser.getRealname(), title);
        //设置图片原始路径
        exportParams.setImageBasePath(upLoadPath);
//        exportParams.setType(ExcelType.HSSF);
        exportParams.setAddIndex(addIndex);

        //获取导出表格字段
//        String exportFields = this.getExportFields(tClass);

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//        mv.addObject(NormalExcelConstants.EXPORT_FIELDS, exportFields);
        mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, tClass);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    public String getExportFields(Class tClass) {
        LoginUser sysUser = JwtUtil.getLoginUser();
        List<String> exportFieldsList = new ArrayList<>();
        //实体类中字段与未授权字段比较，列出需导出字段
        Field[] fileds = ReflectHelper.getAllFields(tClass);
        List<Field> list = new ArrayList(Arrays.asList(fileds));
        for (Field field : list) {
            if (!jeecgPropertyConfig.getBaseDepartId().equalsIgnoreCase(sysUser.getCurrentCompanyId()) && field.getName().equalsIgnoreCase("companyId")) {
                continue;
            }
            exportFieldsList.add(field.getName());
        }
        return exportFieldsList != null && exportFieldsList.size() > 0 ? String.join(CommonConstant.DEFAULT_SEPARATOR, exportFieldsList) : "";
    }

    protected <VO1> List<VO1> importExcelBase(HttpServletRequest request, HttpServletResponse response, Class<VO1> clazz) throws Exception {
        return importExcelBase(request, response, clazz, 2, 1);
    }

    protected <VO1> List<VO1> importExcelBase(HttpServletRequest request, HttpServletResponse response, Class<VO1> clazz, int titleRows, int headRows) throws Exception {
        List<VO1> list = new ArrayList<>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(titleRows);
            params.setHeadRows(headRows);
            params.setNeedSave(true);
            try {
                list.addAll(ExcelImportUtil.importExcel(file.getInputStream(), clazz, params));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }
}
